package cn.bonoon.controllers.fmm;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.bonoon.core.plugins.OwnerService;
import cn.bonoon.entities.OwnerEntity;
import cn.bonoon.kernel.events.DialogEvent;
import cn.bonoon.kernel.menus.ChannelDefinition;
import cn.bonoon.kernel.menus.MenuDefinition;
import cn.bonoon.kernel.support.services.IService;
import cn.bonoon.kernel.web.ButtonEventType;
import cn.bonoon.kernel.web.annotations.grid.GridStandardDefinition;
import cn.bonoon.kernel.web.controllers.AbstractGridController;
import cn.bonoon.kernel.web.handlers.DialogFormInitializer;
import cn.bonoon.kernel.web.handlers.DialogInsertHandler;
import cn.bonoon.kernel.web.models.DialogModel;

@Controller
@RequestMapping("s/sys/owner")
public class OwnerController extends AbstractGridController<OwnerEntity, OwnerItem> {

	private OwnerService service;

	@Autowired
	protected OwnerController(OwnerService service) {
		super(service);
		this.service = service;
	}

	@Override
	protected Class<OwnerItem> itemClass() {
		return OwnerItem.class;
	}

	@Override
	@GridStandardDefinition(updateClass = OwnerUpdate.class, detailClass = OwnerDetail.class, deleteOperation = false)
	protected OwnerService initLayoutGrid(LayoutGridRegister register) throws Exception {
		DialogInsertHandler<OwnerEntity> dih = new DialogInsertHandler<OwnerEntity>(register, service, OwnerInsert.class);
		dih.setFormInitializer(new OwnerFormInitializer());
		dih.register(register.toolbar()).ordinal(0);

		register.button("用户管理", "accounts.do", ButtonEventType.DIALOG).ordinal(20);
		
		return service;
	}

	private class OwnerFormInitializer implements DialogFormInitializer<OwnerEntity> {
		@Override
		public Object init(IService<OwnerEntity> is, DialogModel model, DialogEvent event, Long id, Object form) {
			StringBuilder html = new StringBuilder();
			ChannelDefinition channelInfo = moduleManager.getChannelManager();
			for (MenuDefinition menu : channelInfo) {
				html.append("<option value='").append(menu.getId()).append("'>").append(menu.getName()).append("</option>");
			}
			model.addObject("privilege", html);
			return form;
		}
	}

}
